<template>
  <div class="document-editor-container">
    <!-- 头部工具栏 -->
    <div class="editor-header">
      <div class="left-section">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/knowledge' }">知识管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: `/knowledge/space/${spaceId}` }">{{ spaceName }}</el-breadcrumb-item>
          <el-breadcrumb-item>{{ document.documentName || '新建文档' }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="right-section">
        <el-button-group>
          <el-button type="primary" @click="setViewMode('edit')">
            <el-icon>
              <Edit />
            </el-icon>
            编辑
          </el-button>
        </el-button-group>

        <el-divider direction="vertical" />

        <el-button @click="showVersionHistory = true">
          <el-icon>
            <Clock />
          </el-icon>
          版本历史
        </el-button>



        <el-button type="primary" @click="saveDocument" :loading="saving">
          <el-icon>
            <Check />
          </el-icon>
          保存
        </el-button>

        <el-button @click="goBack">
          <el-icon>
            <Back />
          </el-icon>
          返回
        </el-button>
      </div>
    </div>

    <!-- 文档信息栏 -->
    <div class="document-info" v-if="document.documentId">
      <div class="info-item">
        <span class="label">创建者：</span>
        <span>{{ document.creatorUsername }}</span>
      </div>
      <div class="info-item">
        <span class="label">创建时间：</span>
        <span>{{ formatDate(document.createdAt) }}</span>
      </div>
      <div class="info-item">
        <span class="label">最后编辑：</span>
        <span>{{ formatDate(document.updatedAt) }}</span>
      </div>
      <div class="info-item">
        <span class="label">版本：</span>
        <span>v{{ document.version || 1 }}</span>
      </div>
      <div class="info-item" v-if="editSession">
        <el-tag type="success" size="small">
          <el-icon>
            <EditPen />
          </el-icon>
          编辑中
        </el-tag>
      </div>
    </div>

    <!-- 编辑器主体 -->
    <div class="editor-main">
      <!-- 编辑区域 -->
      <div class="editor-panel">
        <div class="editor-toolbar">
          <div class="toolbar-right">
            <el-switch v-model="autoSaveEnabled" active-text="自动保存" @change="toggleAutoSave" />
            <span class="save-status" v-if="lastSaveTime">
              最后保存: {{ formatTime(lastSaveTime) }}
            </span>
          </div>
        </div>

        <!-- Vditor编辑器容器 -->
        <div id="vditor-editor" class="vditor-editor"></div>
      </div>
    </div>



    <!-- 版本历史对话框 -->
    <el-dialog v-model="showVersionHistory" title="版本历史" width="80%" top="5vh">
      <div class="version-history">
        <el-timeline>
          <el-timeline-item v-for="version in versions" :key="version.versionId"
            :timestamp="formatDate(version.createdAt)" placement="top">
            <el-card>
              <div class="version-header">
                <h4>版本 {{ version.versionNumber }}</h4>
                <div class="version-meta">
                  <span>编辑者: {{ version.editorUsername }}</span>
                  <span v-if="version.editSummary">摘要: {{ version.editSummary }}</span>
                </div>
              </div>
              <div class="version-actions">
                <el-button size="small" @click="previewVersion(version)">
                  预览
                </el-button>
                <el-button size="small" type="primary" @click="restoreVersion(version)">
                  恢复此版本
                </el-button>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 保存版本对话框 -->
    <el-dialog v-model="showSaveDialog" title="保存文档" width="500px">
      <el-form :model="saveForm" label-width="80px">
        <el-form-item label="版本摘要">
          <el-input v-model="saveForm.editSummary" type="textarea" :rows="3" placeholder="描述本次修改的内容..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSaveDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmSave" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, watch, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Edit, Clock, Check, Back,
  Refresh, EditPen, Plus, Minus, Document, Files
} from '@element-plus/icons-vue'
import { documentApi, documentFolderApi } from '@/api/knowledge'
import { useUserStore } from '@/stores/user'
import Vditor from 'vditor'
import 'vditor/dist/index.css'

export default {
  name: 'DocumentEditor',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const userStore = useUserStore()

    // 响应式数据
    const spaceId = ref(route.params.spaceId)
    const documentId = ref(route.params.documentId)
    const spaceName = ref('')
    const viewMode = ref('edit') // edit, preview, split
    const documentContent = ref('')

    const saving = ref(false)
    const autoSaveEnabled = ref(true)
    const lastSaveTime = ref(null)
    const editSession = ref(null)

    const showVersionHistory = ref(false)
    const showSaveDialog = ref(false)
    const versions = ref([])

    // Vditor编辑器实例
    let vditorInstance = null

    const document = reactive({
      documentId: null,
      documentName: '',
      documentType: 'markdown',
      documentDescription: '',
      content: '',
      spaceId: null,
      creatorUsername: '',
      createdAt: null,
      updatedAt: null,
      version: 1
    })

    const saveForm = reactive({
      editSummary: ''
    })

    // 自动保存定时器
    let autoSaveTimer = null

    // 计算属性
    const isNewDocument = computed(() => !documentId.value || documentId.value === 'new')

    // 初始化Vditor编辑器
    const initVditorEditor = async () => {
      await nextTick()

      if (vditorInstance) {
        vditorInstance.destroy()
      }

      vditorInstance = new Vditor('vditor-editor', {
        height: 'calc(100vh - 200px)',
        mode: 'ir', // 即时渲染模式，更稳定
        placeholder: '开始编写你的文档...',
        theme: 'classic',
        icon: 'material',
        outline: {
          enable: true,
          position: 'left'
        },
        preview: {
          delay: 300,
          mode: 'editor',
          hljs: {
            style: 'github',
            lineNumber: true
          },
          math: {
            inlineDigit: true,
            engine: 'KaTeX'
          }
        },
        toolbar: [
          'headings',
          'bold',
          'italic',
          'strike',
          '|',
          'line',
          'quote',
          'list',
          'ordered-list',
          'check',
          'outdent',
          'indent',
          '|',
          'link',
          'table',
          'code',
          'inline-code',
          '|',
          'undo',
          'redo',
          '|',
          'edit-mode',
          {
            name: 'more',
            toolbar: [
              'both',
              'preview',
              'fullscreen',
              'outline',
              'code-theme',
              'content-theme'
            ]
          }
        ],
        cache: {
          enable: false
        },
        counter: {
          enable: true,
          type: 'markdown'
        },
        input: (value) => {
          documentContent.value = value
          onContentChange()
        },
        focus: () => {
          console.log('编辑器获得焦点')
        },
        blur: () => {
          console.log('编辑器失去焦点')
        },
        after: () => {
          console.log('Vditor编辑器初始化完成')
          // 设置初始内容
          if (documentContent.value) {
            vditorInstance.setValue(documentContent.value)
          }
          // 确保outline功能可用
          setTimeout(() => {
            if (vditorInstance && vditorInstance.vditor.outline) {
              console.log('Vditor outline功能已启用')
            }
          }, 100)
        }
      })
    }



    // 方法
    const setViewMode = (mode) => {
      viewMode.value = 'edit'

      // 更新编辑器预览模式为纯编辑模式
      if (vditorInstance) {
        vditorInstance.setPreviewMode('editor')
        // 确保编辑器显示正确内容
        setTimeout(() => {
          if (documentContent.value) {
            vditorInstance.setValue(documentContent.value)
          }
        }, 50)
      }
    }

    const onContentChange = () => {
      if (autoSaveEnabled.value && editSession.value) {
        clearTimeout(autoSaveTimer)
        autoSaveTimer = setTimeout(() => {
          autoSaveDraft()
        }, 2000) // 2秒后自动保存草稿
      }
    }

    const autoSaveDraft = async () => {
      if (!documentId.value || isNewDocument.value) return

      // 从Vditor获取最新内容
      if (vditorInstance) {
        documentContent.value = vditorInstance.getValue()
      }

      try {
        await documentApi.autoSaveDraft(
          documentId.value,
          documentContent.value,
          userStore.user.username,
          editSession.value
        )
        lastSaveTime.value = new Date()
      } catch (error) {
        console.error('自动保存失败:', error)
      }
    }

    const toggleAutoSave = (enabled) => {
      if (enabled && !editSession.value && !isNewDocument.value) {
        startEditSession()
      } else if (!enabled && editSession.value) {
        endEditSession()
      }
    }

    const startEditSession = async () => {
      if (isNewDocument.value) return

      try {
        const response = await documentApi.startEditSession(
          documentId.value,
          userStore.user.username
        )
        editSession.value = response.data
      } catch (error) {
        ElMessage.error('启动编辑会话失败: ' + error.message)
      }
    }

    const endEditSession = async () => {
      if (!editSession.value) return

      try {
        await documentApi.endEditSession(
          editSession.value,
          userStore.user.username
        )
        editSession.value = null
      } catch (error) {
        console.error('结束编辑会话失败:', error)
      }
    }

    const refreshPreview = async () => {
      if (!documentContent.value.trim()) {
        const previewElement = window.document.getElementById('vditor-editor-preview')
        if (previewElement) {
          previewElement.innerHTML = '<div style="color: #999; text-align: center; padding: 50px; font-size: 14px;">暂无内容，开始编写你的文档...</div>'
        }
        return
      }

      loadingPreview.value = true
      try {
        await nextTick()
        const previewElement = window.document.getElementById('vditor-editor-preview')
        if (previewElement) {
          // 清空之前的内容
          previewElement.innerHTML = ''

          // 使用Vditor的预览功能
          Vditor.preview(previewElement, documentContent.value, {
            mode: 'light',
            anchor: {
              enable: true
            },
            lineNumber: false,
            math: {
              inlineDigit: true,
              engine: 'KaTeX'
            },
            hljs: {
              style: 'github',
              lineNumber: true
            }
          })
        }
      } catch (error) {
        const previewElement = window.document.getElementById('vditor-editor-preview')
        if (previewElement) {
          previewElement.innerHTML = '<div style="color: #f56c6c; text-align: center; padding: 50px; font-size: 14px;">预览渲染失败，请检查文档格式</div>'
        }
        console.error('预览失败:', error)
      } finally {
        loadingPreview.value = false
      }
    }

    const renderMarkdown = (content) => {
      // 简单的Markdown渲染，实际项目中可以使用marked.js等库
      return content
        .replace(/^# (.*$)/gim, '<h1>$1</h1>')
        .replace(/^## (.*$)/gim, '<h2>$1</h2>')
        .replace(/^### (.*$)/gim, '<h3>$1</h3>')
        .replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/gim, '<em>$1</em>')
        .replace(/\n/gim, '<br>')
    }



    const saveDocument = () => {
      if (isNewDocument.value) {
        // 新文档直接保存
        createDocument()
      } else {
        // 现有文档显示保存对话框
        showSaveDialog.value = true
      }
    }

    const createDocument = async () => {
      // 从Vditor获取最新内容
      if (vditorInstance) {
        documentContent.value = vditorInstance.getValue()
      }

      if (!documentContent.value.trim()) {
        ElMessage.warning('文档内容不能为空')
        return
      }

      const documentName = await ElMessageBox.prompt('请输入文档名称', '新建文档', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{1,100}$/,
        inputErrorMessage: '文档名称长度应在1-100个字符之间'
      })

      if (!documentName.value) return

      saving.value = true
      try {
        const newDoc = {
          documentName: documentName.value,
          documentType: 'markdown',
          content: documentContent.value,
          spaceId: spaceId.value
        }

        const response = await documentApi.createDocument(
          newDoc,
          userStore.user.username
        )

        ElMessage.success('文档创建成功')
        // 跳转到编辑页面
        router.replace({
          path: `/knowledge/space/${spaceId.value}/document/${response.data.documentId}/edit`
        })
      } catch (error) {
        ElMessage.error('创建文档失败: ' + error.message)
      } finally {
        saving.value = false
      }
    }

    const confirmSave = async () => {
      // 从Vditor获取最新内容
      if (vditorInstance) {
        documentContent.value = vditorInstance.getValue()
      }

      saving.value = true
      try {
        await documentApi.saveDocumentWithVersion(
          documentId.value,
          documentContent.value,
          userStore.user.username,
          saveForm.editSummary
        )

        ElMessage.success('文档保存成功')
        showSaveDialog.value = false
        saveForm.editSummary = ''
        lastSaveTime.value = new Date()

        // 重新加载文档信息
        await loadDocument()
      } catch (error) {
        ElMessage.error('保存文档失败: ' + error.message)
      } finally {
        saving.value = false
      }
    }

    const loadDocument = async () => {
      if (isNewDocument.value) {
        document.spaceId = spaceId.value
        return
      }

      try {
        const response = await documentApi.getDocumentById(
          parseInt(documentId.value),
          userStore.user.username
        )

        Object.assign(document, response.data)
        documentContent.value = document.content || ''

        // 启动编辑会话
        if (autoSaveEnabled.value) {
          await startEditSession()
        }
      } catch (error) {
        ElMessage.error('加载文档失败: ' + error.message)
        goBack()
      }
    }

    const loadVersionHistory = async () => {
      if (isNewDocument.value) return

      try {
        const response = await documentApi.getDocumentVersions(
          documentId.value,
          userStore.user.username
        )
        versions.value = response.data
      } catch (error) {
        ElMessage.error('加载版本历史失败: ' + error.message)
      }
    }

    const previewVersion = (version) => {
      // 在新窗口预览版本内容
      const previewWindow = window.open('', '_blank')
      previewWindow.document.write(`
        <html>
          <head><title>版本预览 - v${version.versionNumber}</title></head>
          <body style="font-family: Arial, sans-serif; padding: 20px;">
            <h1>版本 ${version.versionNumber}</h1>
            <p><strong>编辑者:</strong> ${version.editorUsername}</p>
            <p><strong>时间:</strong> ${formatDate(version.createdAt)}</p>
            <hr>
            <div>${renderMarkdown(version.content)}</div>
          </body>
        </html>
      `)
    }

    const restoreVersion = async (version) => {
      try {
        await ElMessageBox.confirm(
          `确定要恢复到版本 ${version.versionNumber} 吗？当前未保存的修改将丢失。`,
          '确认恢复',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        documentContent.value = version.content

        // 更新Vditor内容
        if (vditorInstance) {
          vditorInstance.setValue(version.content)
        }

        showVersionHistory.value = false
        ElMessage.success('版本恢复成功')
      } catch {
        // 用户取消
      }
    }

    const goBack = () => {
      router.push(`/knowledge/space/${spaceId.value}`)
    }

    const formatDate = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleString('zh-CN')
    }

    const formatTime = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleTimeString('zh-CN')
    }

    // 监听版本历史对话框
    watch(showVersionHistory, (show) => {
      if (show) {
        loadVersionHistory()
      }
    })

    // 生命周期



    onMounted(async () => {
      try {
        await loadDocument()
        await nextTick()
        await initVditorEditor()
      } catch (error) {
        console.error('编辑器初始化失败:', error)
        ElMessage.error('编辑器初始化失败')
      }
    })

    onUnmounted(() => {
      // 清理定时器和编辑会话
      if (autoSaveTimer) {
        clearTimeout(autoSaveTimer)
      }
      if (editSession.value) {
        endEditSession()
      }
      // 销毁Vditor实例
      if (vditorInstance) {
        vditorInstance.destroy()
        vditorInstance = null
      }
    })

    return {
      spaceId,
      documentId,
      spaceName,
      viewMode,
      documentContent,
      saving,
      autoSaveEnabled,
      lastSaveTime,
      editSession,

      showVersionHistory,
      showSaveDialog,
      versions,
      document,
      saveForm,
      isNewDocument,
      initVditorEditor,
      setViewMode,
      onContentChange,
      toggleAutoSave,
      saveDocument,
      confirmSave,
      goBack,
      formatDate,
      formatTime,
      previewVersion,
      restoreVersion
    }
  }
}
</script>

<style scoped>
.document-editor-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.document-info {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 8px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 12px;
  color: #666;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.label {
  font-weight: 500;
}

.editor-main {
  flex: 1;
  display: flex;
  overflow: hidden;
  position: relative;
}

.editor-main.edit .editor-panel {
  width: 100%;
  display: flex;
}

.editor-main.edit .preview-panel {
  display: none;
}

.editor-main.preview .editor-panel {
  display: none;
}

.editor-main.preview .preview-panel {
  width: 100%;
  display: flex;
}

.editor-main.split .editor-panel {
  width: 50%;
  display: flex;
  border-right: 1px solid #e4e7ed;
}

.editor-main.split .preview-panel {
  width: 50%;
  display: flex;
}

.editor-panel,
.preview-panel {
  flex-direction: column;
  background: white;
  min-width: 0;
  overflow: hidden;
}

.editor-toolbar,
.preview-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.save-status {
  font-size: 12px;
  color: #999;
}

.vditor-editor {
  flex: 1;
  height: 100%;
  border: none;
}

.vditor-editor :deep(.vditor) {
  border: none;
  border-radius: 0;
}

.vditor-editor :deep(.vditor-content) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.6;
}

.vditor-editor :deep(.vditor-toolbar) {
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

.vditor-editor :deep(.vditor-preview) {
  background: white;
  padding: 20px;
}

.markdown-preview {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  line-height: 1.6;
}

.markdown-preview :deep(h1),
.markdown-preview :deep(h2),
.markdown-preview :deep(h3) {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-preview :deep(h1) {
  font-size: 2em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 8px;
}

.markdown-preview :deep(h2) {
  font-size: 1.5em;
}

.markdown-preview :deep(h3) {
  font-size: 1.25em;
}

.markdown-preview :deep(p) {
  margin-bottom: 16px;
}

.markdown-preview :deep(code) {
  background: #f6f8fa;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 85%;
}

.markdown-preview :deep(pre) {
  background: #f6f8fa;
  padding: 16px;
  border-radius: 6px;
  overflow-x: auto;
  margin-bottom: 16px;
}



.version-history {
  max-height: 60vh;
  overflow-y: auto;
}

.version-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.version-meta {
  font-size: 12px;
  color: #666;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.version-actions {
  display: flex;
  gap: 8px;
}
</style>